package com.fsj.spring.web;

import Model.Student;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fsj.spring.model.TUser;
import com.fsj.spring.service.IDeptService;
import com.fsj.spring.service.IUserService;
import java.io.IOException;
import java.io.PrintWriter;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.pclong.commons.http.HttpHelper;
import com.pclong.config.entity.CardTypeConfigEntity;
import com.pclong.config.entity.ServerConfigEntity;
import com.pclong.config.entity.ServerState;
import com.pclong.model.ChargeMoneyForIdParamsModel;
import com.pclong.model.ChargeMonyForIdResult;
import com.pclong.model.PlayerRoleModel;
import com.pclong.service.ConfigService;
import com.pclong.service.GeneralService;
import com.pclong.util.Crypto;
import java.util.Iterator;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

@Controller
public class PaymentController {

    private static final Logger log = LogManager.getLogger(WelcomeController.class);

    @RequestMapping(value = "/payment")
    public void PayRequest(HttpServletRequest req, HttpServletResponse res, String serverId, String userName, String areaId, String cardType, String jNetBillId, String sign, String currencyUnit, String userId) throws IOException, Exception {

        String result = "";
        String param = String.format("serverId:%s, userName:%s, areaId:%s, cardType:%s, jNetBillId：%s, sign：%s,UserId:%s", serverId, userName, areaId, cardType, jNetBillId, sign, userId);

        //登陆成功，写日志
        String ip = req.getHeader("x-forwarded-for");  

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  

            ip = req.getHeader("Proxy-Client-IP");  

        }  

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  

            ip = req.getHeader("WL-Proxy-Client-IP");  

        }  

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  

            ip = req.getRemoteAddr();  

        }        

        String userIp = req.getRemoteAddr();
        try {
            //检查服务器功能
            if (false) {
                result = "9";
                throw new Exception("The Server Has Closed PayRequestEnabled Function.");
            }
            if (serverId.isEmpty()) {
                result = "9";
                throw new Exception("ServerId IsNullOrEmpty Error.");
            }
            if (userName.isEmpty()) {
                result = "10";
                throw new Exception("userName IsNullOrEmpty Error.");
            }
            //合区充值需要
            if (userId.isEmpty()) {
                result = "10";
                throw new Exception("userId IsNullOrEmpty Error.");
            }
            if (cardType.isEmpty()) {
                result = "11";
                throw new Exception("cardType IsNullOrEmpty Error.");
            }
            if (jNetBillId.isEmpty()) {
                result = "12";
                throw new Exception("jNetBillId IsNullOrEmpty Error.");
            }
            if (sign.isEmpty()) {
                result = "13";
                throw new Exception("Sign IsNullOrEmpty Error.");
            }

            if (currencyUnit.isEmpty()) {
                currencyUnit = "THB";
            }
            //检查服务器 
            // 服务器不存在或已隐藏
            ServerConfigEntity server = ConfigService.GetServerById(Integer.parseInt(serverId));
            if (server == null || server.State == ServerState.Hidden) {
                result = "9";
                throw new Exception(String.format("while charge，the server is not existing ,serverid:%s", serverId));
            }

            //检查用户
            List<PlayerRoleModel> userResult = GeneralService.GetPlayerRoleList(server.SelectRoleUrl, userName);
            if (userResult == null || userResult.size() < 1) {
                result = "2";
                throw new Exception("Username does not exist.");
            }

            //合区充值需要
            PlayerRoleModel user = null;
            for (Iterator<PlayerRoleModel> u = userResult.iterator(); u.hasNext();) {
                PlayerRoleModel uModel = u.next();
                if (uModel.Id == Integer.parseInt(userId)) {
                    user = uModel;
                    break;
                }
            }
            if (user == null) {
                result = "2";
                throw new Exception("userId error.");
            }
            //验证签名
            String strToVerify = userName + "+" + cardType + "+" + jNetBillId + "+" + Crypto.Decrypt(server.SignKey);
            String signToVerify = HttpHelper.hexDigest(strToVerify);
            if (!signToVerify.toLowerCase().equals(sign.toLowerCase())) {
                result = "14";
                throw new Exception("Sign Error.");
            } else {
                result = "1";
                //查询点卡类型
                CardTypeConfigEntity card = ConfigService.GetCardTypeById(cardType);
                if (card == null) {
                    result = "11";
                    throw new Exception("The CardTpe Is not Exist.");
                }
                //处理充值

                //验证通过 开始发放点卷
                ChargeMoneyForIdParamsModel chargeMoneyParams = new ChargeMoneyForIdParamsModel();

                chargeMoneyParams.ChargeId = jNetBillId;
                chargeMoneyParams.UserName = userName;
                chargeMoneyParams.Userid = userId;
                chargeMoneyParams.Money = Float.toString(card.RealMoney);
                chargeMoneyParams.Point = Float.toString(card.PointMoney);
                chargeMoneyParams.PayWay = cardType;
                chargeMoneyParams.ChargeKey = Crypto.Decrypt(server.ChargeKey);// 解密KEY
                chargeMoneyParams.ChargeUrl = server.ChargeUrl;
                chargeMoneyParams.CurrencyUnit = currencyUnit;


                String respone;
                String chargeResult = GeneralService.RequestChargeMonyForId(chargeMoneyParams);
                if (Integer.parseInt(chargeResult) == ChargeMonyForIdResult.Success.value()) {
                    result = "0";
                    if (log.isInfoEnabled()) {
                        log.info(String.format("充值成功！返回:%s.参数%s", result, param));
                    }
                } else {
                    result = chargeResult;
                    if (log.isInfoEnabled()) {
                        log.info(String.format("充值失败！返回:%s.参数%s", result, param));
                    }
                }
            }

        } catch (Exception ex) {
//            if (logger.IsErrorEnabled) {
//                logger.Error(ex, String.Format("在执行PayRequest方法中发生异常,错误信息：{0},错误代号:{1},参数信息：{2},Ip:{3}", ex.Message, result, param, userIp));
//           
            //}
            result += " Error Message:" + ex.getMessage();
        }
        res.setContentType("text/html;charset=UTF-8");
        PrintWriter out = res.getWriter();
        try {
            /* TODO output your page here*/
            out.println(result);

        } finally {
            out.close();
        }
    }
    @Resource
    public IUserService userService;

    public IUserService getUserService() {
        return userService;
    }

    public void setUserService(IUserService userService) {
        this.userService = userService;
    }
}
